using System.Data;
using System.IO;

namespace SqlPrompt
{
	class DelimitedFileDataTarget : IDataTarget
	{
        public string OutputFilePath { get; set; }

		StreamWriter sw = null;
		string columnDelimiter = ",";
		string rowDelimiter = "\r\n";
		string doubleQuoteReplacement = "\"\"";

        public DelimitedFileDataTarget()
        {
            OutputFilePath = "c:\\temp\\output.csv";
        }

		public void Init(DataColumn[] columns)
		{
            App.Msg("Writing query results to '" + OutputFilePath + "'.");

            sw = new StreamWriter(OutputFilePath);

			string currentDelimiter = "";
			foreach (DataColumn column in columns)
			{
				sw.Write(currentDelimiter + "\"" + FormatValue(column.Name) + "\"");
				currentDelimiter = columnDelimiter;
			}

			sw.Write(rowDelimiter);
		}

		public void WriteRow(IDataReader reader)
		{
			string currentDelimiter = "";
			for (int i = 0; i < reader.FieldCount; i++)
			{
				sw.Write(currentDelimiter + "\"" + FormatValue(reader[i]) + "\"");
				currentDelimiter = columnDelimiter;
			}

			sw.Write(rowDelimiter);
		}

		public void Finish()
		{
			if (sw != null)
				sw.Close();
		}

		string FormatValue(object value)
		{
			if (value is string)
			{
				string s = (string)value;
				s = s.Replace("\"", doubleQuoteReplacement);
				return s;
			}

			return value.ToString();
		}

		public void FlushChunk() { }

		public int ChunkSize { get { return 0; } }
	}
}
